<?php
/**
 * Created by PhpStorm.
 * User: Peco
 * Date: 2019/9/17
 * Time: 20:43
 */

namespace App\Models;

use Dingo\Api\Exception\InternalHttpException;

/**
 * Class GoodsSku
 * @package App\Models
 */
class GoodsSku extends BaseModel
{
    /**
     * 与模型关联的数据表
     *
     * @var string
     */
    protected $table = 'goods_sku';

    /**
     * 主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 需要被转换成日期的属性。
     *
     * @var array
     */
    protected $dates = ['created_at', 'updated_at'];

    /**
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * @var array
     */
    protected $hidden = ['deleted_at'];

    /**
     * @var array
     */
    protected $appends = [];

    /**
     * 减去库存
     * @param $amount
     * @return mixed
     * @throws \Exception
     */
    public function decreaseInventory($amount){
        if ($amount < 0) {
            throw new \Exception('减库存不可小于0');
        }

        return $this->where('id', $this->id)
            ->where('inventory', '>=', $amount)
            ->decrement('inventory', $amount);
    }

    /**
     * 添加库存
     * @param $amount
     * @throws \Exception
     */
    public function addInventory($amount){
        if ($amount < 0) {
            throw new \Exception('加库存不可小于0');
        }
        $this->increment('inventory', $amount);
    }

    /**
     * 所属商品
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function goods(){
        return $this->belongsTo(Goods::class, 'goodsId', 'id');
    }

    /**
     * 库存大于零
     * @param $query
     * @return mixed
     */
    public function scopeInventory($query){
        return $query->whereNotNull('inventory');
    }
}
